package controllers

import (
	"distributed/db"
	"distributed/storage"
	"encoding/json"
	"fmt"
	"golang.org/x/net/websocket"
)

type CommentSong struct {
	//gorm.Model
	SongID    string `json:"song_id"`
	Song      string `json:"song"`
	CommentID int    `json:"commentId"`
	Content   string `json:"content"`
	Time      int64  `json:"time"`

	UserID    int    `json:"userId"`
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatarUrl"`
}

func Comment(conn *websocket.Conn) {
	_chan := make(chan []db.Comment, 1)
	defer close(_chan)
	songName := make(map[string]db.Song)
	for {
		storage.CommentChan <- _chan
		comments := <-_chan
		commentSongs := make([]*CommentSong, len(comments))
		for i, v := range comments {
			var song db.Song
			if s, ok := songName[v.SongID]; ok {
				song = s
			} else {
				db.DB.Where("`song_id` = ?", v.SongID).First(&song)
				songName[v.SongID] = song
			}

			commentSongs[i] = &CommentSong{
				Song:      song.Title,
				SongID:    v.SongID,
				CommentID: v.CommentID,
				Content:   v.Content,
				Time:      v.Time,
				UserID:    v.UserID,
				Nickname:  v.Nickname,
				AvatarURL: v.AvatarURL,
			}
		}

		commentsBytes, _ := json.Marshal(commentSongs)
		if err := websocket.Message.Send(conn, string(commentsBytes)); err != nil {
			fmt.Printf("[ websocket.Message.Send(conn, comments) ] error: %v\n", err)
			if err1 := conn.Close(); err != nil {
				fmt.Printf("[ conn.Close() ] error1: %v\n", err1)
				return
			}
			return
		}
	}
}
